import { createRouter, createWebHistory } from 'vue-router'

// 1. 导入页面组件 - 使用懒加载提高性能
const Home = () => import('@/views/Home.vue')
const Contact = () => import('@/views/Contact.vue')
const Product = () => import('@/views/Product.vue')
const Specification = () => import('@/views/specificationsheet/index.vue')
// const ProductDetail = () => import('@/views/ProductDetail.vue')
// const Blog = () => import('@/views/Blog.vue')
// const BlogDetail = () => import('@/views/BlogDetail.vue')
// const NotFound = () => import('@/views/NotFound.vue')
import type { RouteRecordRaw } from 'vue-router'

// 2. 定义路由规则
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      title: '鑫永业科技 - 首页',
      description: '深圳市鑫永业科技有限公司专业提供编码器芯片解决方案',
    },
  },
  {
    path: '/contact',
    name: 'Contact',
    component: Contact,
    meta: {
      title: '联系我们 - 鑫永业科技',
      description: '获取鑫永业科技的联系方式',
    },
  },
  {
    path: '/specification/:modelNumber(.*)*',
    name: 'Specification',
    component: Specification,
    meta: {
      title: '产品规格书页面',
      description: '用于展示和下载对应的产品规格书',
    },
  },
  {
    path: '/product/:pathMatch(.*)*',
    name: 'Product',
    component: Product,
    meta: {
      title: '产品中心 - 鑫永业科技',
    },
    /*     children: [
      {
        path: 'magnetic',
        name: 'MagneticProducts',
        component: () => import('@/views/products/Magnetic.vue'),
        meta: { title: '磁编码芯片' },
      },
      // 其他产品子路由...
    ], */
  },
  // {
  //   path: '/products/:id',
  //   name: 'ProductDetail',
  //   component: ProductDetail,
  //   props: true,
  //   meta: {
  //     title: '产品详情 - 鑫永业科技',
  //   },
  // },
  // {
  //   path: '/blog',
  //   name: 'Blog',
  //   component: Blog,
  //   meta: {
  //     title: '技术博客 - 鑫永业科技',
  //   },
  // },
  // {
  //   path: '/blog/:slug',
  //   name: 'BlogDetail',
  //   component: BlogDetail,
  //   props: true,
  //   meta: {
  //     title: '博客详情 - 鑫永业科技',
  //   },
  // },
  // // 404页面
  // {
  //   path: '/:pathMatch(.*)*',
  //   name: 'NotFound',
  //   component: NotFound,
  //   meta: {
  //     title: '页面未找到 - 鑫永业科技',
  //   },
  // },
]
console.log('Product 组件:', Product)
// 3. 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) return savedPosition
    if (to.hash) {
      return {
        el: to.hash,
        behavior: 'smooth',
      }
    }
    return { top: 0 }
  },
})

// 4. 全局路由守卫 - 更新页面标题
router.beforeEach((to, from, next) => {
  const metaTitle = to.meta.title
  const metaDescription = to.meta.description

  document.title = metaTitle || '鑫永业科技有限公司'

  const descriptionMeta = document.querySelector('meta[name="description"]')
  if (descriptionMeta && metaDescription) {
    descriptionMeta.setAttribute('content', metaDescription)
  }

  next()
})

export default router
